package cn.wanho.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.wanho.dto.ExamMenuRole;
import cn.wanho.dto.ExamRoles;
import cn.wanho.dto.ExamUser;
import cn.wanho.mapper.ExamMenuRoleMapper;
import cn.wanho.mapper.ExamSummaryMapper;
import cn.wanho.mapper.ExamUserMapper;
import cn.wanho.redis.RedisManger;
import cn.wanho.rvo.*;
import cn.wanho.service.user.UserService;
import cn.wanho.util.PassEnDeUtil;
import cn.wanho.util.TemplateEntity;
import cn.wanho.util.TemplateListener;
import com.alibaba.excel.EasyExcel;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private RedisManger redisManger;

    @Resource
    private ExamUserMapper examUserMapper;

    @Resource
    private ExamMenuRoleMapper examMenuRoleMapper;

    @Resource
    private ExamSummaryMapper examSummaryMapper;

    @Override
    public boolean register(ExamUser user) {
        return false;
    }

    /**
     * 登录功能，将jwt存到 redis中( 修改后，已经交给springsecurity完成 )
     */
//    @Override
//    public ResultVO login(String userName, String userPass) {
//        //通过用户名查用户
//        ExamUser examUser = examUserMapper.selectUserByName(userName);
//        if (examUser == null) {
//            //没有当前用户或者当前用户已不可用
//            return ResultVO.faiure(ResultEnum.USER_ACCOUNT_NOT_EXIST.getResCode(), ResultEnum.USER_ACCOUNT_NOT_EXIST.getResMsg());
//        }
//        String salt = examUser.getSalt();
//        String encoderPass = PassEnDeUtil.encoder(userPass, salt);
//        if (!encoderPass.equals(examUser.getUserPass())) {
//            return ResultVO.faiure(ResultEnum.USER_CREDENTIALS_ERROR.getResCode(), ResultEnum.USER_CREDENTIALS_ERROR.getResMsg());
//        }
//        Long id = examUser.getId();
//        String jwt = JWTUtil01.createJWT(String.valueOf(id), userName, "loginuser", 1000 * 60 * 60 * 24L);
//        redisManger.saveJWT(Math.toIntExact(id), jwt);
//        return ResultVO.success(ResultEnum.SUCCESS.getResCode(), ResultEnum.SUCCESS.getResMsg(), jwt);
//    }

    @Override
    public ResultVO insertAdmin(Integer userId, String userName) {
        String userDefaultPass = "123456";
        UUID salt = UUID.randomUUID();
        String encoderPass = PassEnDeUtil.encoder(userDefaultPass, String.valueOf(salt));
        try {
            examUserMapper.insertAdmin(userId, userName, encoderPass, String.valueOf(salt));
            return ResultVO.success(ResultEnum.CREATE_ADMIN_SUCCESS.getResCode(), ResultEnum.CREATE_ADMIN_SUCCESS.getResMsg());

        } catch (Exception e) {
            e.printStackTrace();
            return ResultVO.faiure(ResultEnum.CREATE_ADMIN_REPEAT.getResCode(), ResultEnum.CREATE_ADMIN_REPEAT.getResMsg());
        }

    }


    /**
     * 修改用户的信息，根据传入的tooken信息,取到用户的id
     *
     * @param id
     * @param userName
     * @param userIcon
     * @param personInfo
     */
    @Override
    public ResultVO updateUserById(Long id, String userName, String userIcon, String personInfo) {
        int i = examUserMapper.updateUserById(userName, userIcon, personInfo, id);
        if (i != 0) {
            return ResultVO.success(ResultEnum.UPDATE_USER_SUCCESS.getResCode(), ResultEnum.UPDATE_USER_SUCCESS.getResMsg());
        } else {
            return ResultVO.faiure(ResultEnum.UPDATE_USER_FAILURE.getResCode(), ResultEnum.UPDATE_USER_FAILURE.getResMsg());
        }
    }

    @Override
    public ResultVO updatePassWord(String oldPass, String newPass, Integer userId) {
        ExamUser examUser = examUserMapper.selectUserByuserId(userId);
        String userPass = examUser.getUserPass();//获取数据库密码
        String salt = examUser.getSalt();
        String encoderPass = PassEnDeUtil.encoder(oldPass, salt);
        UUID salt1 = UUID.randomUUID();
        String np = PassEnDeUtil.encoder(newPass, String.valueOf(salt1));
        if (encoderPass.equals(userPass)) {
            int i = examUserMapper.updatePass(encoderPass, np, userId,String.valueOf(salt1));
            if (i > 0) {
                return ResultVO.success(ResultEnum.UPDATE_USERPASS_SUCCESS.getResCode(), ResultEnum.UPDATE_USERPASS_SUCCESS.getResMsg());
            } else {
                return ResultVO.faiure(ResultEnum.UPDATE_USERPASS_FAILURE.getResCode(), ResultEnum.UPDATE_USERPASS_SUCCESS.getResMsg());
            }
        } else {
            return ResultVO.faiure(ResultEnum.USERPASS_NOT_EXIST.getResCode(), ResultEnum.USERPASS_NOT_EXIST.getResMsg());
        }
    }

    @Override
    public List<ExamMenuRole> selectListByPath(String url) {
        return examUserMapper.selectListByPath(url);
    }

    @Override
    public ExamUser selectByName(String username) {
        return examUserMapper.selectUserByName(username);
    }

    @Override
    public List<ExamMenuRole> selectListByUser(Long id) {
        return examMenuRoleMapper.selectListByUserId(id);
    }

    /**excel*/
    /**
     * @author zxy
     * @date 2022/8/5
     */
    @Override
    public ResultVO importExcel(MultipartFile file, HttpServletRequest request) throws IOException {
        //处理数据
        List<TemplateEntity> entities = getTemplateEntities(file);
        //权限判断你是不是管理员
        Integer userId = (Integer) request.getAttribute("userId");
//        Long parentId = Long.valueOf((String) request.getAttribute("userId"));
        Integer flag = examUserMapper.judge(Long.valueOf(userId));
        if (flag == 1 || flag == 2) {
            //集合数据返回前端
            HashMap<String, String> map = new HashMap<>();
            //遍历存入数据库
            for (TemplateEntity entity : entities) {
                System.out.println(entity);
                System.out.println(entity.getUserName());

                ExamUser examUser = new ExamUser();
                String userName = entity.getUserName();
                String userPass = entity.getUserPass();
                //获取盐-固定的
                String salt = "studentstudent";
                //加密后密码
                String newUserPass = PassEnDeUtil.encoder(userPass, salt);
                //获取创建人 父id
//            Long parentId = Long.valueOf((String) request.getAttribute("userId"));
                //判断存入的id是不是有重复的
                //判断是否已经存在
                Integer integer = examUserMapper.queryTeacherByUserName(userName);
                if (integer == null) {
                    examUser.setParentId(Long.valueOf(userId));
                    examUser.setSalt(salt);
                    examUser.setUserName(userName);
                    examUser.setUserPass(newUserPass);
                    examUser.setPersonInfo(entity.getPersonInfo());
                    //存入
                    int i = examUserMapper.insertSelective(examUser);
                    //改权限为学生---4
                    Integer userid = examUserMapper.SelectUserIdByUserName(userName);
                    Integer i2 = examUserMapper.AddRoles(userid, 4);
                    if (i == 1 && i2 == 1) {
                        //成功
                        map.put(userName, "1-成功");
                    } else {
                        map.put(userName, "2-失败");
                    }
                } else {
                    map.put(userName, "3-此用户名重复");
                }
            }
            return ResultVO.success(ResultEnum.ADD_EXCEL_SUCCESS.getResCode(), ResultEnum.ADD_EXCEL_SUCCESS.getResMsg(), map);
        }
        return ResultVO.success(ResultEnum.INSUFFICIENT_PERMISSIONS.getResCode(), ResultEnum.INSUFFICIENT_PERMISSIONS.getResMsg());
    }

    /**
     * 学生查询个人信息
     * @author jingxu
     * @param id
     */
    @Override
    public ResultVO selectStudentInformation(Long id) {
        /**先要根据id去查当前登录用户的身份是否为学生*/
        ExamRoles examRoles = examUserMapper.selectUserInformation(id);
        if ("学生".equals(examRoles.getRoleName())){
            StudentInformatin studentInformatin = examUserMapper.selectStudentInformation(id);
            if (studentInformatin != null){
                return ResultVO.success(ResultEnum.QUERY_STUDENT_SUCCESS.getResCode(), ResultEnum.QUERY_STUDENT_SUCCESS.getResMsg(),studentInformatin);
            }else {
                return ResultVO.faiure(ResultEnum.QUERY_STUDENT_FAILURE.getResCode(), ResultEnum.QUERY_STUDENT_FAILURE.getResMsg());
            }
        }else {
            return ResultVO.faiure(ResultEnum.NO_MATCH_INFORMATION.getResCode(), ResultEnum.NO_MATCH_INFORMATION.getResMsg());
        }
    }

    /**用于excel*/
    /**
     * @author zxy
     * @date 2022/8/5
     */
    private List<TemplateEntity> getTemplateEntities(MultipartFile file) throws IOException {
        //定义的listener
        TemplateListener listener = new TemplateListener();
        EasyExcel.read(file.getInputStream(), TemplateEntity.class, listener).sheet().doRead();
        //返回所有数据
        return listener.getData();
    }


    /**创建老师*/
    /**
     * @author zxy
     * @date 2022/8/5
     */
    @Override
    public ResultVO createTeacher(String userName, String userPass, HttpServletRequest request) {
        //获取盐
        String salt = IdUtil.simpleUUID();
        //加密后密码
        String newUserPass = PassEnDeUtil.encoder(userPass, salt);
        //获取创建人父id
//        Long userId = Long.valueOf((String) request.getAttribute("userId"));
        Integer userId = (Integer) request.getAttribute("userId");
        Integer flag = examUserMapper.judge(Long.valueOf(userId));
        System.out.println(flag);
        if (flag == 1 || flag == 2) {
            //有权限
            //判断是否已经存在
            Integer integer = examUserMapper.queryTeacherByUserName(userName);
            if (integer == null) {
                //创建老师
                Integer teacher = examUserMapper.createTeacher(Long.valueOf(userId), userName, newUserPass, salt);
                //获取userId
                Integer userId2 = examUserMapper.SelectUserIdByUserName(userName);
                //分配权限---3老师
                Integer integer1 = examUserMapper.AddRoles(userId2, 3);
                if (teacher==1&&integer1==1){
                    return ResultVO.success(ResultEnum.CREATETEACHER_SUCCESS.getResCode(), ResultEnum.CREATETEACHER_SUCCESS.getResMsg());
                }else {
                    return ResultVO.faiure(ResultEnum.CREATETEACHER_FAILURE.getResCode(), ResultEnum.CREATETEACHER_FAILURE.getResMsg());
                }
            }else {
                return ResultVO.faiure(ResultEnum.CREATETEACHER_FAILURE.getResCode(), ResultEnum.CREATETEACHER_FAILURE.getResMsg());
            }
        }
        return ResultVO.faiure(ResultEnum.INSUFFICIENT_PERMISSIONS.getResCode(), ResultEnum.INSUFFICIENT_PERMISSIONS.getResMsg());
    }



    /**
     * @author zjy
     * @data 2022/8/6 13:16
     * @description
     */
    @Override
    public ResultVO queryStudentAllScore(Integer userId) {
        List<ScoreAndTeacherVO> list =  examSummaryMapper.queryStudentScore(userId);
        if(!list.isEmpty()){
            return ResultVO.success(ResultEnum.QUERY_SCORE_TEACHER_SUCCESS.getResCode(), ResultEnum.QUERY_STUDENT_SUCCESS.getResMsg(),list);
        }else{
            return ResultVO.faiure(ResultEnum.QUERY_SCORE_TEACHER_FAILURE.getResCode(), ResultEnum.QUERY_STUDENT_FAILURE.getResMsg());
        }
    }


    /**
     * @author zjy
     * @data 2022/8/7 13:43
     * @description
     */
    @Override
    public ResultVO studentApplyFor(Long subjectId, Integer userId) {
        List<ApplyForVO> list = examSummaryMapper.applyForReconsider(subjectId,userId);
        if(!list.isEmpty()){
            return ResultVO.success(ResultEnum.APPLY_FOR_SUCCESS.getResCode(), ResultEnum.APPLY_FOR_SUCCESS.getResMsg(),list);
        }else{
            return ResultVO.faiure(ResultEnum.APPLY_FOR_FAILURE.getResCode(), ResultEnum.APPLY_FOR_FAILURE.getResMsg());
        }
    }

}
